import akshare as ak
import pandas as pd
import time
import yagmail

# 配置参数
SYMBOL = "J2505"  # 焦炭2505合约
MA20_WINDOW = 20 * 26  # 20日均线窗口（每日26根15分钟K线）
MA80_WINDOW = 80 * 26  # 80日均线窗口
THRESHOLD = 0.015  # 价格偏离阈值1.5%


def get_kline_data():
    """获取实时15分钟K线数据（网页6/7）"""
    df = ak.futures_zh_minute_sina(symbol=SYMBOL, period="15")
    df.rename(columns={
        'date': 'datetime',
        'open': 'Open',
        'high': 'High',
        'low': 'Low',
        'close': 'Close',
        'volume': 'Volume'
    }, inplace=True)
    df['datetime'] = pd.to_datetime(df['datetime'])
    df.set_index('datetime', inplace=True)
    return df[['Open', 'High', 'Low', 'Close', 'Volume']]


def calculate_ma(df):
    """计算双均线（网页1/5）"""
    df['MA20'] = df['Close'].rolling(window=MA20_WINDOW).mean()
    df['MA80'] = df['Close'].rolling(window=MA80_WINDOW).mean()
    return df.dropna()


def check_alert_condition(row):
    """检测报警条件（网页2/4）"""
    close_price = row['Close']
    ma20 = row['MA20']
    ma80 = row['MA80']

    # 双向接近判定条件
    cond_20 = abs(close_price - ma20) / ma20 < THRESHOLD
    cond_80 = abs(close_price - ma80) / ma80 < THRESHOLD

    # 增加成交量验证（网页4）
    volume_cond = row['Volume'] > df['Volume'].rolling(5).mean().iloc[-1] * 1.2
    return cond_20 & cond_80 & volume_cond


def send_alert():
    """邮件报警（需配置SMTP）"""
    yag = yagmail.SMTP(user='your@email.com', password='key')
    content = f'''
    焦炭2505报警触发！
    最新价格：{latest_price}
    20日均线：{ma20_value}
    80日均线：{ma80_value}
    时间：{pd.Timestamp.now().strftime("%Y-%m-%d %H:%M")}
    '''
    yag.send(to='target@email.com', subject='均线接近警报', contents=content)


if __name__ == '__main__':
    while True:
        try:
            # 获取并处理数据
            raw_data = get_kline_data()
            data_with_ma = calculate_ma(raw_data)

            # 检测最新K线
            latest_row = data_with_ma.iloc[-1]
            if check_alert_condition(latest_row):
                print(f"[警报] {pd.Timestamp.now()} 触发条件")
                send_alert()

            # 休眠至下个周期（网页6数据更新频率）
            time.sleep(900 - time.time() % 900)  # 精确15分钟间隔

        except Exception as e:
            print(f"错误: {str(e)}")
            time.sleep(60)
